package com.lmxdawn.api.im.handler;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSON;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.lmxdawn.api.dnf.entity.Order;
import com.lmxdawn.api.dnf.mapper.OrderMapper;
import com.lmxdawn.api.im.service.ImUtil;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.jim.core.ImChannelContext;
import org.jim.core.ImPacket;
import org.jim.core.message.MessageHelper;
import org.jim.core.packets.ChatBody;
import org.jim.core.packets.ChatType;
import org.jim.core.packets.Message;
import org.jim.server.JimServerAPI;
import org.jim.server.command.CommandManager;
import org.jim.server.config.ImServerConfig;
import org.jim.server.processor.chat.BaseAsyncChatMessageProcessor;
import org.jim.server.util.ChatKit;
import org.redisson.api.RedissonClient;

import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

import static org.jim.core.packets.Command.*;

@Slf4j
public class MessageProcessor extends BaseAsyncChatMessageProcessor {
    LoadingCache<String, Order> loadingCache = CacheBuilder.newBuilder()
            .maximumSize(200).expireAfterAccess(5*60, TimeUnit.SECONDS)
            .build(new CacheLoader<String, Order>() {
                @Override
                public Order load(String groupId) throws Exception {
                    return SpringUtil.getBean(OrderMapper.class).selectByPrimaryKey(groupId);
                }
            });

    @Override
    protected void doProcess(ChatBody chatBody, ImChannelContext imChannelContext) {
        // 处理消息 ，把改群组消息往前移

        var groupId = chatBody.getGroupId();
        String from = chatBody.getFrom();
        // 新消息提示 ->
        ChatBody build = ChatBody.newBuilder()
                .chatType(chatBody.getChatType())
                .groupId(chatBody.getGroupId())
                .from(chatBody.getFrom())
                .to(chatBody.getTo())
                .content(chatBody.getContent())
                .setCmd(99)
                .msgType(chatBody.getMsgType())
                .build();
        ImPacket imPacket = new ImPacket(COMMAND_UNKNOW, JSON.toJSONString(build).getBytes());
        try {
            if (groupId.startsWith("user-")){
                JimServerAPI.sendToGroup(groupId, imPacket);
            }else{
                Order order = loadingCache.get(groupId);
                log.info("sendToGroup====>{},{}", order, from);
                if (from != null && from.equals(order.getSaleId())){
                    JimServerAPI.sendToGroup(order.getUserId() + "-notify" , imPacket);
                }else{
                    JimServerAPI.sendToGroup(order.getSaleId() + "-notify", imPacket);
                }
            }
        } catch (ExecutionException e) {
        }
        var messageHelper = ((ImServerConfig) imChannelContext.getImConfig()).getMessageHelper();
        var groupUsers = messageHelper.getGroupUsers(groupId);
        log.info("groupUsers: {}", groupUsers);
        if ("0".equals(from) || "客服".equals(from) || "admin".equals(from)){
            return ;
        }
        if (StrUtil.isNotBlank(from) && !StrUtil.equals("null", from)){
            ImUtil.moveUserToFirst(from);
        }
        JimServerAPI.sendToGroup("0", imPacket);
    }


    @Override
    public void process(ImChannelContext imChannelContext, Message message) {
        ChatBody chatBody = (ChatBody)message;
        //开启持久化
        boolean isStore = ImServerConfig.ON.equals(imServerConfig.getIsStore());
        if(isStore){
            //存储群聊消息;
            if(ChatType.CHAT_TYPE_PUBLIC.getNumber() == chatBody.getChatType()){
                pushGroupMessages(PUSH, STORE, chatBody, isStore);
            }else{
                String from = chatBody.getFrom();
                String to = chatBody.getTo();
                String sessionId = ChatKit.sessionId(from,to);
                writeMessage(STORE,USER+":"+sessionId,chatBody);
                boolean isOnline = ChatKit.isOnline(to, isStore);
                if(!isOnline){
                    writeMessage(PUSH,USER+":"+to+":"+from,chatBody);
                }
            }
        }
        doProcess(chatBody, imChannelContext);
    }

    /**
     * 推送持久化群组消息
     * @param pushTable
     * @param storeTable
     * @param chatBody
     */
    private void pushGroupMessages(String pushTable, String storeTable , ChatBody chatBody, boolean isStore){
        MessageHelper messageHelper = imServerConfig.getMessageHelper();
        String group_id = chatBody.getGroupId();
        //先将群消息持久化到存储Timeline;
        writeMessage(storeTable,GROUP+":"+group_id,chatBody);
        List<String> userIds = messageHelper.getGroupUsers(group_id);
        //通过写扩散模式将群消息同步到所有的群成员
        for(String userId : userIds){
            boolean isOnline = false;
            if(isStore && ImServerConfig.ON.equals(imServerConfig.getIsCluster())){
                isOnline = messageHelper.isOnline(userId);
            }else{
                isOnline = ChatKit.isOnline(userId, isStore);
            }
            if(!isOnline){
                writeMessage(pushTable, GROUP+":"+group_id+":"+userId, chatBody);
            }
        }
        if (!StrUtil.equals(chatBody.getFrom(), "客服")){
            writeMessage(pushTable, GROUP+":"+group_id+":客服", chatBody);
        }
    }

    public void writeMessage(String timelineTable , String timelineId , ChatBody chatBody){
        MessageHelper messageHelper = imServerConfig.getMessageHelper();
        messageHelper.writeMessage(timelineTable, timelineId, chatBody);
    }
}
